
import subprocess
# 转换为 HTML
input_html ='temp.html'

# 在这里添加自定义的 HTML 处理逻辑
# 例如：调整标题级别，处理特定的样式等



# 将处理后的 HTML 转换为 Markdown
subprocess.run(['pandoc', '-f', 'html', '-t', 'markdown_strict+pipe_tables+table_captions+yaml_metadata_block', input_html  , '-o', 'output.md'])



import os
import subprocess
from typing import Dict, Any, Union
from pathlib import Path

def html_to_markdown(input_filepath: str, output_filepath: str, options: Dict[str, Any] = {}) -> Dict[str, Union[bool, str, Any]]:
    """
    Convert HTML file to Markdown using pandoc.

    :param input_filepath: Path to the input HTML file.
    :param output_filepath: Path to the output Markdown file.
    :param options: A dictionary of optional parameters.
    :return: A dictionary containing the result of the operation.

    Return value structure:
    {
        'success': bool,  # True if the operation was successful, False otherwise
        'error': str,     # Error message if an error occurred, empty string otherwise
        'data': Any,      # Any additional data or results from the operation
        'metadata': Dict[str, Any]  # Additional metadata about the operation
    }
    """
    result = {
        'success': False,
        'error': '',
        'data': None,
        'metadata': {}
    }

    try:
        # Validate input file
        if not os.path.exists(input_filepath):
            raise FileNotFoundError(f"Input file not found 找不到输入文件: {input_filepath}")

        # Create output directory if it doesn't exist
        output_dir = os.path.dirname(output_filepath)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir)
            result['metadata']['created_output_dir'] = output_dir

        # Example of processing logic
        print(f"Input file: {input_filepath}")
        print(f"Output file: {output_filepath}")
        print(f"Options: {options}")

        # Add your processing logic here
        # For example:
        pandoc_options = options.get('pandoc_options', ['-f', 'html', '-t', 'markdown_strict+pipe_tables+table_captions+yaml_metadata_block'])

        # Convert HTML to Markdown using pandoc
        subprocess.run(['pandoc'] + pandoc_options + [input_filepath, '-o', output_filepath], check=True)

        # If processing is successful:
        result['success'] = True
        result['data'] = "HTML file successfully converted to Markdown"
        result['metadata'].update({
            'input_filepath': input_filepath,
            'output_filepath': output_filepath,
            'pandoc_options': pandoc_options,
            'input_size': os.path.getsize(input_filepath),
            'output_size': os.path.getsize(output_filepath)
        })

    except subprocess.CalledProcessError as e:
        result['error'] = f"Pandoc conversion failed: {str(e)}"
        result['metadata']['error_type'] = type(e).__name__
    except Exception as e:
        result['error'] = str(e)
        result['metadata']['error_type'] = type(e).__name__

    return result

def test(arg={}):
    # Usage example
    input_path = "input.html"
    output_path = "output/converted.md"
    options = {
        "pandoc_options": ['-f', 'html', '-t', 'markdown_strict+pipe_tables+table_captions+yaml_metadata_block']
    }

    result = html_to_markdown(input_path, output_path, options)
    print(result)

# Uncomment the following line to run the test function
# test()
